import os
import time

from flask import Blueprint, request, jsonify, make_response, json
from flask_restful import Api,Resource
from flask import current_app as app
from uitils.comm import get_data
from db import db1
from uitils.acl import aci
from uitils.jwton import jwte
from uitils.redison import red


qianname = Blueprint('qianname',__name__)


@qianname.route('/workflow')
def workflow():
    sql = "select * from workflow"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})


@qianname.route('/getcoursedata')
def getcoursedata():
    # 先从redis中取数据
    key = 'coursedata'
    value = red.set_get_str(key)
    if value:
        list = eval(value)

    else:
        # 如果redis中不存在,去数据库中查询
        sql = "select * from data_source"
        res = db1.findall(sql)
        list = []
        if res:
            for i in res:
                dict = {'id':i['id'],'name':i['name']}
                sql1 = "select id,name,type from %s"%(i['tablename'])
                res1 = db1.findall(sql1)
                dict['mes'] = res1
                list.append(dict)

        # 存入redis
        red.set_str(key,json.dumps(list))
    return jsonify({'code':200,'list':list})



@qianname.route('/addcoursedata',methods=['POST'])
def addcoursedata():
    id = request.args.get('id')
    data = get_data()
    sql = "update workflow set params='{}' where id={}".format(data['data'],int(id))
    print(sql)
    db1.update(sql)
    return jsonify({'code':200,'msg':'添加成功'})


@qianname.route('/getrespid',methods=['GET','POST'])
def getrespid():
    if request.method == 'POST':
        data = get_data()
        sql = "insert into resources(name,url,status,pid) values('{}','{}',{},{})".format(data['name'],data['url'],int(data['status']),int(data['pid']))
        db1.update(sql)
        return jsonify({'code': 200, 'msg': '添加成功'})
    else:
        sql = "select * from resources where pid=0"
        res = db1.findall(sql)
        return jsonify({'code':200,'list':res})



@qianname.route('/getparams')
def getparams():
    id = request.args.get('id')
    sql = "select * from workflow where id={}".format(int(id))
    res = db1.find(sql)
    return jsonify({'code':200,'list':res})


@qianname.route('/imgfile',methods=['POST'])
def imgfile():
    file = request.files['file']
    file.save(os.path.join('./static/iimg/' + file.filename))
    img = 'http://localhost:5000/static/iimg/' + file.filename
    return jsonify({'code': 200, 'list': img})

@qianname.route('/submit_task',methods=['GET','POST'])
def submit_task():
    if request.method == 'POST':
        data =get_data()
        print(data)
        sql = "select * from workflow where id={}".format(int(data['wid']))
        res = db1.find(sql)
        tt = data['姓名']+res['name']
        params = json.dumps(data)
        sql1 = "insert into task(id,title,review) values(0.'%s','%s')" %(tt,data['ids'])
        print(sql1)
        db1.update(sql1)
        return jsonify({'code':200,'msg':'添加成功'})


def getdeptdata(data):
    tree = {}
    list = []
    for i in data:
        tree[i['id']] = i
    for j in data:
        pid = j['pid']
        if not pid:
            j['type'] = 1
            list.append(j)
        else:
            if 'children' not in tree[pid]:
                tree[pid]['children'] = []
            # 查询此部门下所有员工
            sql = "select * from users where bum_id=%d" % (j['id'])
            res = db1.findall(sql)
            userlist = []
            if res:
                for u in res:
                    u['type'] = 3
                    userlist.append(u)
            j['children'] = userlist
            j['type'] = 2
            tree[pid]['children'].append(j)

    return list


@qianname.route('/getcomanyuser')
def getcomanyuser():
    # 获取所有公司及所有部门
    sql = "select * from dept"
    res = db1.findall(sql)
    mes = getdeptdata(res)
    return jsonify({'code': 200, 'list': mes})
    # 数据重组，查询员工


@qianname.route('/taskm', methods=['POST'])
def taskm():
    data = get_data()
    # print(data)
    title = data['title']
    params = data['params']
    list = []
    for  (i,value)  in data.items():
        if i[:-3]=='auditids':
            list.append(int(value))


    # 添加任务
    sql = "insert into task(title,params,rev,status,next_nev) values('%s','%s','%s',1,%d)" % (
    title, params, list, int(list[0]))
    db1.update(sql)

    sql1 = "select id,title from task where title='%s'" % (title)
    task = db1.find(sql1)
    # 把当前任务加到redis中，选用hash类型
    key = 'task%d' % (list[0])
    red.hash_set(key, task['id'], task['title'])
    return jsonify({"code": 200,'msg':'成功'})


# 待我审批
@qianname.route('/mytaskaudit')
def mytaskaudit():
    id = request.args.get('id')
    # 从redis中获取我的任务列表
    key = 'task%d' % (int(id))
    print(key)
    task = red.hash_get_all(key)
    list = []
    for k, v in task.items():
        id = k
        title = v
        list.append({'id': id, 'title': title})

    return jsonify({"code": 200, 'list': list})


@qianname.route('/get_mytask')
def get_mytask():
    id = request.args.get('id')
    sql = "select * from task where next_nev={}".format(int(id))
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})


@qianname.route('/mytaskhandle')
def mytaskhandle():
    time.sleep(1)
    userid = request.args.get('userid')
    if userid:
        sql = "select * from task where user_id=%d" % (int(userid))
        res = db1.findall(sql)
        return jsonify({"code": 200, 'list': res})

    id = request.args.get('id')
    sql = "select * from task where id=%d" % (int(id))

    task = db1.find(sql)
    # 此任务相关的审批记录
    sql1 = "select * from audit_record where task_id=%d" % (int(id))
    records = db1.findall(sql1)
    return jsonify({"code": 200, 'list': task,'records':records})


import datetime
@qianname.route('/taskrecordM',methods=['POST'])
def taskrecordM():
    data = get_data()
    #写审批记录表
    time = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
    try:
        sql = "insert into audit_record(task_id,user_id,username,is_agree,reason,add_time) values(%d,%d,'%s',%d,'%s','%s')" % (
        int(data['taskid']), int(data['userid']), data['name'], int(data['agree']), data['reason'], time)

        db1.add(sql)
    except:
        return jsonify({"code": 10010, 'mes': '审批失败'})

    # 判断是否同意
    tsql = "select * from task where id=%d" % (int(data['taskid']))
    task = db1.find(tsql)
    key = 'task%d' % (int(data['userid']))
    # 清除当前redis中的信息
    red.hash_del_value(key, int(data['taskid']))
    auditlist = json.loads(task['rev'])
    # 是不是最后一个审批人
    index = auditlist.index(int(data['userid']))
    if data['agree'] == '1':
        try:
            # 同意，查询任务，更新下一审批人，redis清除当前审批人，加入下一审批人，
            # 任务表中更新任务状态，如果是最后一个审批人，查新成已经完成，其它审核中
            if index == len(auditlist) - 1:
                sql1 = "update task set status=3,next_nev=0 where id=%d" % (int(data['taskid']))
                db1.add(sql1)
            else:
                sql1 = "update task set status=2,next_nev=%d where id=%d" % (auditlist[index + 1], int(data['taskid']))
                db1.add(sql1)
                # 添加redis
                newkey = 'task%d' % (int(auditlist[index + 1]))
                # 把下一审批人加入到redis
                red.hash_set(newkey, int(data['taskid']), task['title'])
            db1.commit()
        except:
            db1.rollback()
            return jsonify({"code": 10020, 'mes': '失败'})
    else:
        # 不同意，把redis中当前审批人清除，任务表中的下一审批人清空
        if index == 0:
            sql1 = "update task set status=1,next_nev=0 where id=%d" % (int(data['taskid']))
            db1.update(sql1)
        else:
            sql1 = "update task set next_nev=%d where id=%d" % (int(auditlist[index - 1]), int(data['taskid']))
            db1.update(sql1)
            # 添加redis
            newkey = 'task%d' % (int(auditlist[index - 1]))
            # 把下一审批人加入到redis
            red.hash_set(newkey, int(data['taskid']), task['title'])
    return jsonify({"code": 200})

@qianname.route('/noticem',methods=['POST'])
def noticem():
    data = get_data()
    print(data)
    list = []
    for (i, value) in data.items():
        if i[:-3] == 'values':
            list.append(int(value))
    now = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
    # 添加通知表
    sql = "insert into notice(title,notice_type,content,type,level,ctime) values('{}',{},'{}',{},{},'{}')".format(data['title'],int(data['notice_type']),data['content'],int(data['type']),int(data['level']),now)
    id = db1.update(sql)
    if int(data['type']) == 3:
        for i in list:
            sql1 = "insert into notice_record(notice_id,user_id,ctime) values({},{},'{}')".format(int(id),int(i),now)
            db1.update(sql1)

    return jsonify({'code':200,'msg':'添加成功'})

@qianname.route('/getnotice')
def getnotice():
    userid = request.args.get('id')
    sql = "select * from notice where type=1 or id in(select notice_id from notice_record where user_id={}) order by ctime desc,level asc".format(int(userid))
    res = db1.findall(sql)
    mes = []

    for i in res:
        i['status'] = 0
        # 消息发给所有人
        if int(i['type']) == 1:
            # 点击进入详情页,在详情页里更新redis set
            key = 'notice'+str(i['id'])
            # 此条消息的已读列表
            list = red.set_get_set(key)
            if list:
                if userid in list:
                    i['status'] = 1
        if int(i['type']) == 3:
            sql2 = "select * from notice_record where notice_id={} and user_id={}".format(int(i['id']),int(userid))
            res1 = db1.find(sql2)
            if res1:
                i['status'] = 1
        mes.append(i)
    return jsonify({'code':200,'lsit':mes})


@qianname.route('/updatenotice',methods=['POST'])
def updatenotice():
    # 获取信息
    data = get_data()
    # 查看消息类型,如果消息类型为1,想redis中添加数据
    sql = "select * from notice where id={}".format(int(data['noticeid']))
    notice = db1.find(sql)
    if int(notice['type']) == 1:
        key = 'notice' + str(notice['id'])
        red.set_add_one(key,int(data['user_id']))
    # 如果消息为3 更新数据库
    if int(notice['type']) == 3:
        sql = "update notice_record set status=1 where notice_id={} and user_id={}".format(int(data['notice_id']),int(data['user_id']))
        db1.update(sql)
    return jsonify({'code':200})